import { SM4, SM3 } from 'gm-crypto';
const key = "0XPFodWjKnPHbam0"; // 前后端一致即可,后端提供
/*
 * GM4加密工具函数
 * @param {String} text 待加密文本
 */
export function SM3encrypt(text: string) {
  return SM3.digest(text,'utf8', 'hex')
}

/*
 * GM4加密工具函数
 * @param {String} text 待加密文本
 */
export function SM4encrypt(text: string | null) {
  console.log(stringToHex32(key))
  return SM4.encrypt(text, stringToHex32(key), {
    // iv,
    mode: SM4.constants.ECB,
    inputEncoding: 'utf8',
    outputEncoding: 'hex'
  })
}

/*
 * GM4解密工具函数
 * @param {String} text 待解密密文
 */
export function SM4decrypt(text: string) {
  return SM4.decrypt(text, key, {
    // iv,
    // mode: SM4.constants.CBC,
    inputEncoding: 'hex',
    outputEncoding: 'utf8'
  })
}

/**
 * 转HEX32位
 * @param {String} str 
 */
export function stringToHex32(str:string) {
  const encoder = new TextEncoder();
  const bytes = encoder.encode(str);
  let hexStr = '';
  for (const byte of bytes) {
    hexStr += byte.toString(16).padStart(2, '0');
  }
  return hexStr;
}

/**
 * 解析GET参数
 * @param {object} obj 
 */
export function getStr(obj:object) {
  let url: string = '';
  for (const propName of Object.keys(obj)) {
    const value = obj[propName];
    let part: string = encodeURIComponent(propName) + "=";
    if (value !== null && typeof (value) !== "undefined" && value) {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          let params: string = propName + '[' + key + ']';
          let subPart: string = encodeURIComponent(params) + "=";
          url += subPart + encodeURIComponent(value[key]) + "&";
        }
      } else {
        url += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return url = url.slice(0, -1);
}